# -*- coding: utf-8 -*-
from src.com.bsjs.util.base_util import BaserUtil
from src.com.bsjs.util.excel_util import WriteExcel
from src.com.bsjs.util.sql_util import MySQLUtils
from src.com.ydzy.util.file_util import FileClient


class Import:
    def __init__(self):
        self.mysql_client = MySQLUtils()
        self.file_client = FileClient()
        self.base_client = BaserUtil()
        self.import_table='param_data'

    def import_data(self, param):
        condition=f"type='{param}'"
        datas=self.mysql_client.retrieve_json(table=self.import_table,condition=condition)
        heads,head_keys,type=self.get_heads(datas)
        data=self.get_data(datas,head_keys)
        return heads,data,type

    def import_file(self, heads,datas, param,type):
        writeExcel = WriteExcel(f"{type}.xlsx",'default')
        writeExcel.add_title(type)
        writeExcel.add_list(heads, datas)
        writeExcel.save()

    def get_heads(self, datas):
        field_dict= self.base_client.json2obj(datas[0]['field_dict'])
        result=[item['coldisplay'] for item in field_dict]
        result2=[item['colname'] for item in field_dict]
        type=datas[0]['type_zh']
        return result,result2,type

    def get_data(self, datas,head_keys):
        result = []
        for data in datas:
            field_data = self.base_client.json2obj(data['field_data'])
            tmp={}
            for head_key in head_keys:
                tmp[head_key]=field_data[head_key]
            # real_data=[field_data[item] for item in head_keys]
            result.append(tmp)
        return result


def main():
    this = Import()
    params=['CusMerchElement']
    for param in params:
        heads,data,type=this.import_data(param)
        this.import_file(heads,data,param,type)






if __name__ == '__main__':
    main()